// 订阅/发布类
class Subscriber {
  constructor() {
    this.subscribers = {}
  }
  on(event, listener) {
    let subscribers = this.subscribers[event]
    if(!subscribers) {
      subscribers = this.subscribers[event] = []
    }
    if(subscribers.every(callback => callback !== listener)){
      subscribers.push(listener)
    }
    return this
  }
  off(event, listener) {
    let subscribers = this.subscribers[event]
    if(subscribers) {
      for(const i = 0; i < subscribers.length; i++) {
        if(subscribers[i] === listener) {
          subscriberss.splice(i, 1);
          break;
        }
      }
    }
    return this
  }
  emit(event, payload) {
    let subscribers = this.subscribers[event]
    subscribers && subscribers.forEach(listener => {
      listener.call(this, payload);
    })
    return this
  }
}

